/*
	Deferred shading example - opengl tools
 
	MIT License

	Copyright (c) 2010, Markus Broecker <mbrckr@gmail.com>

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
 */


#include <iostream>
#include <cstdlib>
#include <map>

#include <OpenGL.h>
#include <Framebuffer.h>
#include <Shader.h>

using namespace glTools;

static Framebuffer*			gGBuffer;
static Shader*				gGBufferCalculate;

static Shader*				gPassthrough;

static Framebuffer*			gRendertarget;
static Shader*				gDeferredLighting;

static float				gAnimation;
static unsigned int			gTimestamp;

/// A list with registered textures. Makes it easier to select one
typedef std::map<std::string, unsigned int> TextureList;
TextureList					gTextureList;
TextureList::const_iterator	gCurrentTexture;


static void renderScene()
{
	// Bind the G-Buffer shader and set up the camera
	gGBufferCalculate->bind();
	gGBufferCalculate->setUniform("camera.position", 10.f, 10.f, 10.f);
	gGBufferCalculate->setUniform("camera.at", 0.f, 0.f, 0.f);
	gGBufferCalculate->setUniform("camera.up", 0.f, 1.f, 0.f);
	gGBufferCalculate->setUniform("camera.fov", 45.f);
	gGBufferCalculate->setUniform("camera.ratio", 1.f);
	gGBufferCalculate->setUniform("camera.near", 1.f);
	gGBufferCalculate->setUniform("camera.far", 100.f);
	
	// use the modelview as dedicated model matrix
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	
	// render ground plane
	glBegin(GL_QUADS);
	glColor3f(0.6, 0.6, 0.6);
	glNormal3f(0.f, 1.f, 0.f);
	glVertex3i(-20, 0, -20);
	glVertex3i(-20, 0, 20);
	glVertex3i(20, 0, 20);
	glVertex3i(20, 0, -20);
	glEnd();
	
	glColor3f(0.6, 0.4, 0.1);
	// The teapot is defined by clockwise polygons!
	glFrontFace(GL_CW);
	glTranslatef(0.f, 1.f, 0.f);
	glRotatef(gAnimation, 0.f, 1.f, 0.f);
	glutSolidTeapot(2.f);
	glFrontFace(GL_CCW);
	
	gGBufferCalculate->disable();
}

/// Renders a quad with texture coordinates 
static void renderFullScreenQuad()
{
	glBegin(GL_QUADS);
	glColor3ub(255, 255, 255);
	glTexCoord2i(0, 1);
	glVertex2i(-1, 1);
	glTexCoord2i(0, 0);
	glVertex2i(-1, -1);
	glTexCoord2i(1, 0);
	glVertex2i(1, -1);
	glTexCoord2i(1, 1);
	glVertex2i(1, 1);
	glEnd();
}

static void display()
{
	// Enable and clear the G-Buffer and render the scene into it.
	gGBuffer->bind();
	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
	
	glEnable(GL_DEPTH_TEST);
	renderScene();
	
	gGBuffer->disable();
	glError();
	
	
	/* 	Prepare for fullscreen quad processing, similar to GPGPU. No depth 
		check needed/wanted as we draw just on top of each other.
	*/
	glDisable(GL_DEPTH_TEST);
	
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(-1, 1, -1, 1, 0, 1);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	
	
	// compose the final image
	gRendertarget->bind();
	
	gDeferredLighting->bind();
	gDeferredLighting->setTexture2D("position", gGBuffer->getColorbuffer(0), 0);
	gDeferredLighting->setTexture2D("normal", gGBuffer->getColorbuffer(1), 1);
	gDeferredLighting->setTexture2D("albedo", gGBuffer->getColorbuffer(2), 2);
	
	renderFullScreenQuad();
	
	gDeferredLighting->disable();
	gRendertarget->disable();
	glError();
	
	
	// display the final render target (note: this is selected by the user)
	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
	
	gPassthrough->bind();
	gPassthrough->setTexture2D("colormap", gCurrentTexture->second);
	
	renderFullScreenQuad();
	
	gPassthrough->disable();
	
	// End of the frame
	glutSwapBuffers();
	glError();
}

static void idle()
{
	unsigned int time = glutGet(GLUT_ELAPSED_TIME);
	float delta = static_cast<float>(time - gTimestamp) / 1000.f;
	gTimestamp = time;
	
	gAnimation += delta * 20.f;
	
	glutPostRedisplay();
}

/**	Handles keyboard inputs. Currently it recognises two: Escape quits the 
	program, Space switches to the next texture.
*/
static void keyboard(unsigned char key, int x, int y)
{
	if (key == 27)
		exit(0);
		
	if (key == ' ')
	{
		++gCurrentTexture;
		
		if (gCurrentTexture == gTextureList.end())
			gCurrentTexture = gTextureList.begin();
	
		std::cout << "Current texture: " << gCurrentTexture->first << "(" << gCurrentTexture->second << ")" << std::endl;	
	}
}


int main(int argc, const char** argv)
{
	glutInit(&argc, const_cast<char**>(argv));
	glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE);
	glutInitWindowSize(512, 512);
	
	glutCreateWindow("Deferred Shading");
	
	glutIdleFunc(idle);
	glutDisplayFunc(display);
	glutKeyboardFunc(keyboard);
	
	std::cout << "Deferred shading gltools example. View different buffers by pressing [SPACE].\n";
	
	// Create all shaders and fbos
	gGBufferCalculate = new Shader("gbuffer.vert", "gbuffer.frag");
	
	// final output
	gRendertarget = new Framebuffer(512, 512, Framebuffer::RGB, Framebuffer::UNSIGNED_BYTE);
	// Note that floats are very slow, but make this example easy.
	gGBuffer = new Framebuffer(256, 256, Framebuffer::RGB, Framebuffer::FLOAT, 3);
	
	gPassthrough = new Shader("passthrough.vert", "passthrough.frag");
	gDeferredLighting = new Shader("passthrough.vert", "deferredlighting.frag");
	
	
	// fill the texture list
	gTextureList["Display Target"] = gRendertarget->getColorbuffer(0);
	gTextureList["G-Buffer Position"] = gGBuffer->getColorbuffer(0);
	gTextureList["G-Buffer Normal"] = gGBuffer->getColorbuffer(1);
	gTextureList["G-Buffer Albedo"] = gGBuffer->getColorbuffer(2);

	gCurrentTexture = gTextureList.begin();
	
	glClearColor(0, 0, 0, 0);
	
	glutMainLoop();
	return 0;
}